#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
API路由模块

提供WebDAV服务的RESTful API接口
"""

from typing import List, Optional, Dict, Any
from fastapi import APIRouter, HTTPException, Depends, status
from fastapi.security import HTTPBasic, HTTPBasicCredentials
from pydantic import BaseModel

from ...models.user import WebDAVUser, WebDAVUserRepository
from ...vfs import VFSClient
from ...common.database import get_sqlalchemy_manager, get_db_session
from ...common.unified_logging import get_logger


# 创建路由器
api_router = APIRouter()

# 基本认证
security = HTTPBasic()

# 日志记录器
logger = get_logger('API')


# Pydantic模型
class UserInfo(BaseModel):
    """用户信息"""
    username: str
    is_active: bool
    created_at: Optional[str] = None
    last_login: Optional[str] = None


class UserCreate(BaseModel):
    """创建用户"""
    username: str
    password: str
    is_active: bool = True


class UserUpdate(BaseModel):
    """更新用户"""
    password: Optional[str] = None
    is_active: Optional[bool] = None


class CloudAccountInfo(BaseModel):
    """云盘账号信息"""
    id: int
    cloud_provider: str
    cloud_account: str
    display_name: str
    is_active: bool
    created_at: Optional[str] = None


class CloudAccountCreate(BaseModel):
    """创建云盘账号"""
    cloud_provider: str = "tianyi"
    cloud_account: str
    cloud_password: str
    display_name: Optional[str] = None


class CloudAccountUpdate(BaseModel):
    """更新云盘账号"""
    cloud_password: Optional[str] = None
    display_name: Optional[str] = None
    is_active: Optional[bool] = None


class ServiceStatus(BaseModel):
    """服务状态"""
    status: str
    webdav_enabled: bool
    vfs_connected: bool
    user_count: int
    uptime: Optional[str] = None


class FileInfo(BaseModel):
    """文件信息"""
    name: str
    path: str
    is_directory: bool
    size: Optional[int] = None
    modified_time: Optional[str] = None


# 依赖注入
def get_user_repository() -> WebDAVUserRepository:
    """获取用户仓库"""
    db_manager = get_sqlalchemy_manager()
    session = db_manager.get_session()
    return WebDAVUserRepository(session)


def get_current_user(
    credentials: HTTPBasicCredentials = Depends(security),
    user_repo: WebDAVUserRepository = Depends(get_user_repository)
) -> WebDAVUser:
    """获取当前用户"""
    user = user_repo.authenticate(credentials.username, credentials.password)
    if not user:
        raise HTTPException(
            status_code=status.HTTP_401_UNAUTHORIZED,
            detail="用户名或密码错误",
            headers={"WWW-Authenticate": "Basic"},
        )
    return user


# API端点
@api_router.get("/status", response_model=ServiceStatus)
async def get_service_status(
    user_repo: WebDAVUserRepository = Depends(get_user_repository)
):
    """获取服务状态"""
    try:
        user_count = user_repo.count_active_users()
        
        return ServiceStatus(
            status="running",
            webdav_enabled=True,
            vfs_connected=True,  # TODO: 实际检查VFS连接状态
            user_count=user_count,
            uptime="N/A"  # TODO: 实现运行时间统计
        )
    except Exception as e:
        logger.error(f"获取服务状态失败: {e}")
        raise HTTPException(status_code=500, detail="获取服务状态失败")


@api_router.get("/users", response_model=List[UserInfo])
async def list_users(
    current_user: WebDAVUser = Depends(get_current_user),
    user_repo: WebDAVUserRepository = Depends(get_user_repository)
):
    """获取用户列表"""
    try:
        users = user_repo.find_all()
        return [
            UserInfo(
                username=user.username,
                is_active=user.is_active,
                created_at=user.created_at.isoformat() if user.created_at else None,
                last_login=user.last_login.isoformat() if user.last_login else None
            )
            for user in users
        ]
    except Exception as e:
        logger.error(f"获取用户列表失败: {e}")
        raise HTTPException(status_code=500, detail="获取用户列表失败")


@api_router.post("/users", response_model=UserInfo)
async def create_user(
    user_data: UserCreate,
    current_user: WebDAVUser = Depends(get_current_user),
    user_repo: WebDAVUserRepository = Depends(get_user_repository)
):
    """创建用户"""
    try:
        # 检查用户是否已存在
        existing_user = user_repo.find_by_username(user_data.username)
        if existing_user:
            raise HTTPException(status_code=400, detail="用户名已存在")
        
        # 创建新用户
        new_user = user_repo.create_user(
            username=user_data.username,
            password=user_data.password,
            is_active=user_data.is_active
        )
        
        return UserInfo(
            username=new_user.username,
            is_active=new_user.is_active,
            created_at=new_user.created_at.isoformat() if new_user.created_at else None
        )
    except HTTPException:
        raise
    except Exception as e:
        logger.error(f"创建用户失败: {e}")
        raise HTTPException(status_code=500, detail="创建用户失败")


@api_router.get("/users/{username}", response_model=UserInfo)
async def get_user(
    username: str,
    current_user: WebDAVUser = Depends(get_current_user),
    user_repo: WebDAVUserRepository = Depends(get_user_repository)
):
    """获取用户信息"""
    try:
        user = user_repo.find_by_username(username)
        if not user:
            raise HTTPException(status_code=404, detail="用户不存在")
        
        return UserInfo(
            username=user.username,
            is_active=user.is_active,
            created_at=user.created_at.isoformat() if user.created_at else None,
            last_login=user.last_login.isoformat() if user.last_login else None
        )
    except HTTPException:
        raise
    except Exception as e:
        logger.error(f"获取用户信息失败: {e}")
        raise HTTPException(status_code=500, detail="获取用户信息失败")


@api_router.put("/users/{username}", response_model=UserInfo)
async def update_user(
    username: str,
    user_data: UserUpdate,
    current_user: WebDAVUser = Depends(get_current_user),
    user_repo: WebDAVUserRepository = Depends(get_user_repository)
):
    """更新用户信息"""
    try:
        user = user_repo.find_by_username(username)
        if not user:
            raise HTTPException(status_code=404, detail="用户不存在")
        
        # 更新用户信息
        if user_data.password is not None:
            user_repo.update_password(username, user_data.password)
        
        if user_data.is_active is not None:
            user_repo.update_status(username, user_data.is_active)
        
        # 重新获取更新后的用户信息
        updated_user = user_repo.find_by_username(username)
        
        return UserInfo(
            username=updated_user.username,
            is_active=updated_user.is_active,
            created_at=updated_user.created_at.isoformat() if updated_user.created_at else None,
            last_login=updated_user.last_login.isoformat() if updated_user.last_login else None
        )
    except HTTPException:
        raise
    except Exception as e:
        logger.error(f"更新用户信息失败: {e}")
        raise HTTPException(status_code=500, detail="更新用户信息失败")


@api_router.delete("/users/{username}")
async def delete_user(
    username: str,
    current_user: WebDAVUser = Depends(get_current_user),
    user_repo: WebDAVUserRepository = Depends(get_user_repository)
):
    """删除用户"""
    try:
        user = user_repo.find_by_username(username)
        if not user:
            raise HTTPException(status_code=404, detail="用户不存在")
        
        # 不能删除自己
        if user.username == current_user.username:
            raise HTTPException(status_code=400, detail="不能删除当前用户")
        
        user_repo.delete_user(username)
        return {"message": "用户删除成功"}
    except HTTPException:
        raise
    except Exception as e:
        logger.error(f"删除用户失败: {e}")
        raise HTTPException(status_code=500, detail="删除用户失败")


# 云盘账号管理API
@api_router.get("/accounts", response_model=List[CloudAccountInfo])
async def list_cloud_accounts(
    current_user: WebDAVUser = Depends(get_current_user)
):
    """获取云盘账号列表"""
    try:
        from ...webdav.models import CloudAccount
        
        with get_session() as session:
            accounts = session.query(CloudAccount).all()
            return [
                CloudAccountInfo(
                    id=account.id,
                    cloud_provider=account.cloud_provider,
                    cloud_account=account.cloud_account,
                    display_name=account.display_name,
                    is_active=account.is_active,
                    created_at=account.created_at.isoformat() if account.created_at else None
                )
                for account in accounts
            ]
    except Exception as e:
        logger.error(f"获取云盘账号列表失败: {e}")
        raise HTTPException(status_code=500, detail="获取云盘账号列表失败")


@api_router.post("/accounts", response_model=CloudAccountInfo)
async def create_cloud_account(
    account_data: CloudAccountCreate,
    current_user: WebDAVUser = Depends(get_current_user)
):
    """创建云盘账号"""
    try:
        from ...webdav.models import CloudAccount
        
        with get_session() as session:
            # 检查账号是否已存在
            existing = session.query(CloudAccount).filter_by(
                cloud_account=account_data.cloud_account
            ).first()
            
            if existing:
                raise HTTPException(status_code=400, detail="账号已存在")
            
            # 创建新账号
            account = CloudAccount(
                cloud_provider=account_data.cloud_provider,
                cloud_account=account_data.cloud_account,
                cloud_password=account_data.cloud_password,
                display_name=account_data.display_name or account_data.cloud_account,
                is_active=True
            )
            
            session.add(account)
            session.commit()
            
            return CloudAccountInfo(
                id=account.id,
                cloud_provider=account.cloud_provider,
                cloud_account=account.cloud_account,
                display_name=account.display_name,
                is_active=account.is_active,
                created_at=account.created_at.isoformat() if account.created_at else None
            )
    except HTTPException:
        raise
    except Exception as e:
        logger.error(f"创建云盘账号失败: {e}")
        raise HTTPException(status_code=500, detail="创建云盘账号失败")


@api_router.get("/accounts/{account_id}", response_model=CloudAccountInfo)
async def get_cloud_account(
    account_id: int,
    current_user: WebDAVUser = Depends(get_current_user)
):
    """获取云盘账号信息"""
    try:
        from ...webdav.models import CloudAccount
        
        with get_session() as session:
            account = session.query(CloudAccount).filter_by(id=account_id).first()
            if not account:
                raise HTTPException(status_code=404, detail="账号不存在")
            
            return CloudAccountInfo(
                id=account.id,
                cloud_provider=account.cloud_provider,
                cloud_account=account.cloud_account,
                display_name=account.display_name,
                is_active=account.is_active,
                created_at=account.created_at.isoformat() if account.created_at else None
            )
    except HTTPException:
        raise
    except Exception as e:
        logger.error(f"获取云盘账号信息失败: {e}")
        raise HTTPException(status_code=500, detail="获取云盘账号信息失败")


@api_router.put("/accounts/{account_id}", response_model=CloudAccountInfo)
async def update_cloud_account(
    account_id: int,
    account_data: CloudAccountUpdate,
    current_user: WebDAVUser = Depends(get_current_user)
):
    """更新云盘账号信息"""
    try:
        from ...webdav.models import CloudAccount
        
        with get_session() as session:
            account = session.query(CloudAccount).filter_by(id=account_id).first()
            if not account:
                raise HTTPException(status_code=404, detail="账号不存在")
            
            # 更新账号信息
            if account_data.cloud_password is not None:
                account.cloud_password = account_data.cloud_password
            
            if account_data.display_name is not None:
                account.display_name = account_data.display_name
            
            if account_data.is_active is not None:
                account.is_active = account_data.is_active
            
            session.commit()
            
            return CloudAccountInfo(
                id=account.id,
                cloud_provider=account.cloud_provider,
                cloud_account=account.cloud_account,
                display_name=account.display_name,
                is_active=account.is_active,
                created_at=account.created_at.isoformat() if account.created_at else None
            )
    except HTTPException:
        raise
    except Exception as e:
        logger.error(f"更新云盘账号信息失败: {e}")
        raise HTTPException(status_code=500, detail="更新云盘账号信息失败")


@api_router.delete("/accounts/{account_id}")
async def delete_cloud_account(
    account_id: int,
    current_user: WebDAVUser = Depends(get_current_user)
):
    """删除云盘账号"""
    try:
        from ...webdav.models import CloudAccount
        
        with get_session() as session:
            account = session.query(CloudAccount).filter_by(id=account_id).first()
            if not account:
                raise HTTPException(status_code=404, detail="账号不存在")
            
            session.delete(account)
            session.commit()
            
            return {"message": "账号删除成功"}
    except HTTPException:
        raise
    except Exception as e:
        logger.error(f"删除云盘账号失败: {e}")
        raise HTTPException(status_code=500, detail="删除云盘账号失败")


@api_router.get("/files", response_model=List[FileInfo])
async def list_files(
    path: str = "/",
    current_user: WebDAVUser = Depends(get_current_user)
):
    """列出文件"""
    try:
        # TODO: 实现文件列表功能
        # 这里需要集成VFS客户端来获取文件列表
        return [
            FileInfo(
                name="示例文件夹",
                path="/example",
                is_directory=True,
                size=None,
                modified_time="2024-01-01T00:00:00"
            ),
            FileInfo(
                name="示例文件.txt",
                path="/example.txt",
                is_directory=False,
                size=1024,
                modified_time="2024-01-01T00:00:00"
            )
        ]
    except Exception as e:
        logger.error(f"列出文件失败: {e}")
        raise HTTPException(status_code=500, detail="列出文件失败")